import torch
import torch.nn  as nn
from   torch.hub import load_state_dict_from_url

class VGG(nn.Module):
    def __init__(self, features, num_classes=1000):
        super(VGG, self).__init__()
        self.features   = features
        self.avgpool    = nn.AdaptiveAvgPool2d((7, 7))
        self.classifier = nn.Sequential(nn.Linear(512 * 7 * 7, 4096),
                            nn.ReLU(True),
                            nn.Dropout(),
                            nn.Linear(4096, 4096),
                            nn.ReLU(True),
                            nn.Dropout(),
                            nn.Linear(4096, num_classes),
                        )
        self._initialize_weights()

    def forward(self, x):
        feat1 = self.features[  :4 ](x)
        feat2 = self.features[4 :9 ](feat1)
        feat3 = self.features[9 :16](feat2)
        feat4 = self.features[16:23](feat3)
        feat5 = self.features[23:-1](feat4)
        return feat1, feat2, feat3, feat4, feat5

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)


def make_layers(cfg, batch_norm=False, in_channels = 3):
    layers = []
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)

cfgs = { # input:  3, 512, 512
    'D': [64, 64, 'M',       # [1, 64,  512, 512]
        128, 128, 'M',       # [1, 128, 256, 256]
        256, 256, 256, 'M',  # [1, 256, 128, 128]
        512, 512, 512, 'M',  # [1, 512, 64,  64]
        512, 512, 512, 'M'   # [1, 512, 32,  32]
    ]
}

# pretrained_url = "https://download.pytorch.org/models/vgg16-397923af.pth"
def VGG16(pretrained, in_channels=3, **kwargs):
    model = VGG(make_layers(cfgs["D"], batch_norm=False, in_channels=in_channels), **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(kwargs.get("pretrained_url"), model_dir="./model_data")
        model.load_state_dict(state_dict)
    
    del model.avgpool
    del model.classifier
    return model

if __name__ == "__main__":
    model  = VGG16(pretrained=False)
    input  = torch.randn((1, 3, 512, 512), dtype=torch.float32)
    output = model(input)
    # [torch.Size([1, 64, 512, 512]), torch.Size([1, 128, 256, 256]), 
    # torch.Size([1, 256, 128, 128]), torch.Size([1, 512, 64, 64]), 
    # torch.Size([1, 512, 32, 32])]
    print([o.shape for o in output])
    
    torch.onnx.export(model, args=(input,), f = "vggnet16.onnx",
                    input_names   = ['input'],
                    output_names  = ['output1', 'output2', 'output3', 'output4', 'output5'],
                    opset_version = 12,
                    dynamic_axes  = None
    )